package com.sto.stoapp.adapter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.sto.stoapp.activity.R;
import com.sto.stoapp.activity.scanner.inquiry.InquiryQueryTable;
import com.sto.stoapp.db.StoDataBaseOperation;
import com.sto.stoapp.entity.ScanRecordInfoEntity;
import com.sto.stoapp.listener.OnBackClickListener;
import com.sto.stoapp.manager.UnSentPictureManager;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.UnifiedStaticType;
import com.sto.stoapp.widget.BaseActivity;
import com.sto.stoapp.widget.BaseDialog;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 扫描记录信息显示
 *
 * @author huangbing
 *
 */
public class RecordInfoMenuAdapter extends BaseAdapter {

	private Context context;
	private List<ScanRecordInfoEntity> menuList;
	private EnumTableNames TABLE_STATUS;
	private int Counter = 0;
	OnDelListener mOnDelListener;
	boolean needJiPaoQi = false;

	/**
	 * 构造函数
	 *
	 * @param context
	 * @param list
	 * @param TABLE_STATUS
	 */
	public RecordInfoMenuAdapter(Context context,
								 List<ScanRecordInfoEntity> list, EnumTableNames TABLE_STATUS,
								 boolean needJiPaoQi) {
		this.context = context;
		this.menuList = list;
		this.TABLE_STATUS = TABLE_STATUS;
		this.needJiPaoQi = needJiPaoQi;

	}

	public void counterAdd() {
		this.Counter++;
	}

	public void counterDel() {
		Counter--;
	}

	@Override
	public int getCount() {
		return menuList == null ? 0 : menuList.size();

	}

	@Override
	public Object getItem(int position) {
		return menuList.get(position);
	}

	@Override
	public long getItemId(int position) {

		return position;
	}

	@Override
	public View getView(final int position, View view, ViewGroup parent) {

		final Holder holder;
		final int count = menuList.size();
		if (count <= 0)
			return view;
		if (view == null) {
			holder = new Holder();
			int resource;
			if (needJiPaoQi) {
				resource = R.layout.jipaoqi_list_item;
			} else {
				resource = R.layout.sto_scan_record_info_menu;
			}
			view = LayoutInflater.from(context).inflate(resource, null);
			holder.recordNumber = (TextView) view
					.findViewById(R.id.record_number);
			holder.recordCode = (TextView) view.findViewById(R.id.record_code);
			holder.weight = (TextView) view.findViewById(R.id.weight);
			holder.cancelImage = (ImageView) view
					.findViewById(R.id.cancel_image);
			if(needJiPaoQi){
				holder.high = (TextView) view
						.findViewById(R.id.high);
				holder.lenght = (TextView) view
						.findViewById(R.id.lenght);
				holder.wide = (TextView) view
						.findViewById(R.id.wide);
				holder.volume = (TextView) view
						.findViewById(R.id.volume);
			}
			view.setTag(holder);
			holder.cancelImage.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {
					final int maxItem = menuList.size();
					final int currItem = (Integer) view.getTag();

					final String currCode = menuList
							.get(maxItem - currItem - 1).getRecordCode();

					deleteEvent(maxItem, currItem, currCode);

				}
			});

		} else {
			holder = (Holder) view.getTag();
		}
		// count - position
		int t = Counter - position;
		if (t <= 0)
			t = 1;
		ScanRecordInfoEntity scanEntity=menuList.get(count - position - 1);
		holder.recordNumber.setText(t + "");
		holder.recordCode.setText(scanEntity
				.getRecordCode());
		holder.cancelImage.setImageResource(scanEntity
				.getImageId());
		String weight = scanEntity.getWeight();
		if(needJiPaoQi){
			holder.weight.setText("重量:"+weight);
			holder.lenght.setText("长:"+scanEntity.getLenght());
			holder.wide.setText("宽:"+scanEntity.getWide());
			holder.high.setText("高:"+scanEntity.getHight());
			holder.volume.setText("体积:"+scanEntity.getVolume());
		}else{
			if (weight != null)
				holder.weight.setText(weight);
		}

		holder.cancelImage.setTag(position);
		return view;
	}

	public void deleteEvent(final int maxItem, final int currItem,
							final String currCode) {
		// SoundManager.getInstance(context).playTitleSound();
		final BaseDialog dialog = new BaseDialog(context);
		dialog.setTitles("确定删除该单号！\n" + currCode);
		dialog.setDefalutLayout1();
		dialog.show();
		dialog.setOnBackClickListener(new OnBackClickListener() {

			@Override
			public void onBackClickListener(boolean res) {
				if (!res) {
					// deletePicture(currCode);
					// 装袋&发件特殊处理
					delBaggingAndSsendpiece(currCode);
					// 删除订单提取
					if (TABLE_STATUS == EnumTableNames.STATUS_TABLE_SALESMAN_ORDER_EXTRACT) {
						StoDataBaseOperation
								.getInstance(context)
								.deleteScanData(
										EnumTableNames.STATUS_TABLE_SALESMAN_RECEIVE
												.ordinal(), currCode);
						updateUnSendCount(1);
					}

					//Add by wj
					if(TABLE_STATUS == EnumTableNames.STATUS_TABLE_SALESMAN_SIGN){
						StoDataBaseOperation.getInstance(context)
								.deleteScanData(EnumTableNames.STATUS_TABLE_SALESMAN_HELP_SIGN.ordinal(),currCode);
						updateUnSendCount(1);
					}

					delLoadCarSendPiece(currCode);
					int delCount = StoDataBaseOperation.getInstance(context)
							.deleteScanData(TABLE_STATUS.ordinal(), currCode);
					// 删除选中扫描数据
					if (delCount > 0) {
						// 回调删除的单号
						if (mOnDelListener != null) {
							mOnDelListener.DelListener(currCode);
						}
						// 获得当前删除的序号
						/*
						 * String currCount = menuList .get(maxItem - currItem -
						 * 1).getRecordNumber();
						 */
						updateUnSendCount(delCount);
						menuList.remove(maxItem - currItem - 1);

						/* 删除记录后重新排序号--start-- */
						Log.d("Recoordmadapter", "[maxItem=" + +maxItem
								+ "] [currItem=" + currItem + "]");
						if (maxItem > 2 && currItem > 0) {
							for (int i = 0; i < (maxItem - currItem - 1); i++) {
								// Integer.parseInt(currCount)
								menuList.get(maxItem - currItem - 1)
										.setRecordNumber(
												String.valueOf(Counter + i));
							}
						}
						Counter--;
						/* --end-- */
						RecordInfoMenuAdapter.this.notifyDataSetChanged();
					} else {
						Helper.showToast(context, context
								.getString(R.string.del_fail_already_upload));
					}
				}
				dialog.dismiss();
			}

		});
	}

	public void setOnDelListener(OnDelListener listener) {
		mOnDelListener = listener;
	}

	public interface OnDelListener {
		void DelListener(String code);
	}

	private void deletePicture(String code) {
		if (TABLE_STATUS == EnumTableNames.STATUS_TABLE_SALESMAN_SIGN
				|| TABLE_STATUS == EnumTableNames.STATUS_TABLE_PROBLEM
				|| TABLE_STATUS == EnumTableNames.STATUS_TABLE_AVIATION_PROBLEM) {
			// if (TABLE_STATUS ==
			// TABLE_NAME_STATUS.STATUS_TABLE_AVIATION_PROBLEM) {
			// TABLE_STATUS = TABLE_NAME_STATUS.STATUS_TABLE_PROBLEM;
			// }
			if (StoDataBaseOperation.getInstance(context).deletePicture(
					TABLE_STATUS.ordinal(), code)) {
				UnSentPictureManager.getInstance(context).deletePictureCount();
			}
		}
	}

	private void delBaggingAndSsendpiece(String code) {
		// 装袋&发件特殊处理
		if (TABLE_STATUS == EnumTableNames.STATUS_TABLE_BAGGINGADNSENDPIECE) {
			// 统计袋号的个数
			int count = StoDataBaseOperation.getInstance(context)
					.StatisticsBagNumberCount(TABLE_STATUS, code);
			if (count == 1) {
				String bagNumber = StoDataBaseOperation.getInstance(context)
						.getBagNumber(TABLE_STATUS, code);
				StoDataBaseOperation
						.getInstance(context)
						.deleteScanData(
								EnumTableNames.STATUS_TABLE_SCANNING_BAGGING_OPERATE
										.ordinal(), bagNumber);
				updateUnSendCount(1);
			}
			// StoDataBaseOperation.getInstance(context).deleteScanData(
			// EnumTableNames.STATUS_TABLE_SCANNING_SENDPIECE.ordinal(),
			// code, ScanTypeEntity.TYPE_SCAN_BAGANDSEND);
			// updateUnSendCount(1);
		}
		// 中转-装袋&发件特殊处理
		else if (TABLE_STATUS == EnumTableNames.STATUS_TABLE_CENTER_BAGGINGADNSENDPIECE) {
			// 统计袋号的个数
			int bag_count = StoDataBaseOperation.getInstance(context)
					.StatisticsBagNumberCount(TABLE_STATUS, code);
			if (bag_count == 1) {
				String bagNumber = StoDataBaseOperation.getInstance(context)
						.getBagNumber(TABLE_STATUS, code);
				StoDataBaseOperation
						.getInstance(context)
						.deleteScanData(
								EnumTableNames.STATUS_CENTER_TABLE_BAGGING_OPERATE
										.ordinal(), bagNumber);
				updateUnSendCount(1);
			}
		}
		else if (TABLE_STATUS == EnumTableNames.STATUS_TABLE_AVIATION_SCAN_PACKET_SEND) {
			int bag_count = StoDataBaseOperation.getInstance(context)
					.StatisticsBagNumberCount(TABLE_STATUS, code);
			if (bag_count == 1) {
				String bagNumber = StoDataBaseOperation.getInstance(context)
						.getBagNumber(TABLE_STATUS, code);
				StoDataBaseOperation
						.getInstance(context)
						.deleteScanData(
								EnumTableNames.STATUS_TABLE_AVIATION_PACKAGE_OPERATE
										.ordinal(), bagNumber);
				updateUnSendCount(1);
			}
		} else {
		}

	}

	private void delLoadCarSendPiece(String currCode) {

		// 统计铅封号的个数
		int leadSealingcount = StoDataBaseOperation.getInstance(context)
				.StatisticsBagNumberCount(TABLE_STATUS, currCode);

		// 删除航空-扫描-装车发件记录
		if (TABLE_STATUS == EnumTableNames.STATUS_TABLE_AVIATION_LOADCAR_SENDPIECE) {
			if (leadSealingcount == 1) {
				String leadSealingCode = StoDataBaseOperation.getInstance(
						context).getBagNumber(TABLE_STATUS, currCode);
				// 删除铅封操作记录
				StoDataBaseOperation
						.getInstance(context)
						.deleteScanData(
								EnumTableNames.STATUS_TABLE_AVIATION_LEAD_SEALING_OPERATE
										.ordinal(), leadSealingCode);
				updateUnSendCount(1);

			}
			// 删除发件记录
			// if (StoDataBaseOperation.getInstance(context).deleteScanData(
			// EnumTableNames.STATUS_TABLE_AVIATION_SCAN_SEND.ordinal(),
			// currCode, ScanTypeEntity.TYPE_SCAN_UPCAR)) {
			// updateUnSendCount(1);
			// }
		}
		// 删除-中转-装车发件记录
		if (TABLE_STATUS == EnumTableNames.STATUS_TABLE_CENTER_LOADCAR_SENDPIECE) {
			if (leadSealingcount == 1) {
				String leadSealingCode = StoDataBaseOperation.getInstance(
						context).getBagNumber(TABLE_STATUS, currCode);
				// 删除铅封操作记录
				StoDataBaseOperation
						.getInstance(context)
						.deleteScanData(
								EnumTableNames.STATUS_TABLE_CENTER_LEAD_SEALING_OPERATE
										.ordinal(), leadSealingCode);
				updateUnSendCount(1);

			}
		}
		if (TABLE_STATUS == EnumTableNames.STATUS_TABLE_LOADCAR_SENDPIECE) {

			if (leadSealingcount == 1) {
				String leadSealingCode = StoDataBaseOperation.getInstance(
						context).getBagNumber(TABLE_STATUS, currCode);
				// 删除铅封操作记录
				StoDataBaseOperation
						.getInstance(context)
						.deleteScanData(
								EnumTableNames.STATUS_TABLE_SCANNING_LEAD_SEALING_OPERATE
										.ordinal(), leadSealingCode);
				updateUnSendCount(1);

			}
		}
	}

	public void showRecordInfo(final String code, final int maxItem,
							   final int currItem) {

		String[] textMenu;

		final String tablename = TABLE_STATUS.getTableName();// 表名
		SimpleDateFormat sDateFormat = new SimpleDateFormat(
				UnifiedStaticType.DATE_TIME_FORMAT);
		String date = sDateFormat.format(new java.util.Date());
		String arrays[] = date.split(" ");
		final InquiryQueryTable querytable = new InquiryQueryTable(context);
		textMenu = querytable.getCodeInquiryDetail(tablename, code, arrays[1],
				TABLE_STATUS.ordinal());
		if (textMenu == null) {
			Helper.showToast(context, "不存在或者已经删除");
			return;
		}
		AlertDialog.Builder builder = new AlertDialog.Builder(this.context);
		builder.setTitle("记录详情").setIcon(android.R.drawable.ic_dialog_info)
				.setNegativeButton("删除", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.dismiss();

						deleteEvent(maxItem, currItem, code);
					}
				}).setItems(textMenu, null);

		builder.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(DialogInterface dialog, int keyCode,
								 KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_DEL
						&& event.getAction() == KeyEvent.ACTION_UP) {
					dialog.dismiss();
					deleteEvent(maxItem, currItem, code);
				} else if (keyCode == KeyEvent.KEYCODE_MENU
						&& event.getAction() == KeyEvent.ACTION_UP) {
					dialog.dismiss();

				}
				return false;
			}
		});
		builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();

				// deleteEvent(maxItem, currItem, code);
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();
	}

	private void updateUnSendCount(int count) {
		BaseActivity activ = (BaseActivity) context;
		activ.deleteCodeNumber(count);
	}

	class Holder {

		TextView recordNumber;
		TextView recordCode;
		TextView weight;
		TextView high;
		TextView wide;
		TextView volume;
		TextView lenght;
		ImageView cancelImage;
	}

}
